using UnityEngine;

public class MouseFollower : MonoBehaviour
{
    [Header("生成设置")]
    public GameObject objectToSpawn; // 要生成的物体预制体
    public LayerMask groundLayer;    // 地面层级，用于射线检测
    public float spawnHeight = 0.5f; // 生成物体离地面的高度

    [Header("跟随设置")]
    public float rotationSpeed = 5f; // 旋转速度
    public bool faceMovementDirection = true; // 是否朝向移动方向

    private GameObject spawnedObject; // 已生成的物体
    private Camera mainCamera;        // 主摄像机
    private Vector3 targetPosition;   // 目标位置
    private Transform hitTransform;   // 射线击中的物体

    void Start()
    {
        mainCamera = Camera.main;

        // 如果没有指定预制体，创建一个默认立方体
        if (objectToSpawn == null)
        {
            Debug.LogWarning("没有指定生成物体，将创建默认立方体");
            objectToSpawn = GameObject.CreatePrimitive(PrimitiveType.Cube);
            objectToSpawn.transform.localScale = Vector3.one * 0.5f;
            objectToSpawn.SetActive(false);
        }

        // 初始生成物体
        SpawnObjectAtScreenCenter();
    }

    void Update()
    {
        // 持续更新目标位置
        UpdateTargetPosition();

        // 如果有生成的物体，让它移动到目标位置
        if (spawnedObject != null)
        {
            MoveObjectToTarget();
        }
    }

    /// <summary>
    /// 在屏幕中心射线落点生成物体
    /// </summary>
    void SpawnObjectAtScreenCenter()
    {
        UpdateTargetPosition();

        if (targetPosition != Vector3.zero)
        {
            // 如果已有物体，先销毁
            if (spawnedObject != null)
            {
                Destroy(spawnedObject);
            }

            // 生成新物体
            spawnedObject = Instantiate(objectToSpawn, targetPosition, Quaternion.identity);
            Debug.Log("物体已生成在: " + targetPosition);
        }
    }

    /// <summary>
    /// 更新目标位置（屏幕中心射线落点）
    /// </summary>
    void UpdateTargetPosition()
    {
        Vector2 screenCenterPoint = new Vector2(Screen.width / 2f, Screen.height / 2f);
        Ray ray = mainCamera.ScreenPointToRay(screenCenterPoint);

        if (Physics.Raycast(ray, out RaycastHit hit, 999f, groundLayer))
        {
            targetPosition = hit.point + Vector3.up * spawnHeight;
            hitTransform = hit.transform;
        }

    }

    /// <summary>
    /// 移动物体到目标位置
    /// </summary>
    void MoveObjectToTarget()
    {
        // if (targetPosition != Vector3.zero)
        // {
        //     // 直接同步位置（不使用Lerp平滑）
        //     spawnedObject.transform.position = targetPosition;

        //     // 如果需要，让物体朝向移动方向
        //     if (faceMovementDirection)
        //     {
        //         Vector3 moveDirection = (targetPosition - spawnedObject.transform.position).normalized;
        //         if (moveDirection != Vector3.zero)
        //         {
        //             Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
        //             spawnedObject.transform.rotation = Quaternion.Slerp(
        //                 spawnedObject.transform.rotation,
        //                 targetRotation,
        //                 rotationSpeed * Time.deltaTime
        //             );
        //         }
        //     }
        // }
    }

    /// <summary>
    /// 销毁已生成的物体
    /// </summary>
    void DestroySpawnedObject()
    {
        if (spawnedObject != null)
        {
            Destroy(spawnedObject);
            spawnedObject = null;
            Debug.Log("物体已销毁");
        }
    }

    /// <summary>
    /// 在编辑器中可视化射线检测
    /// </summary>
    void OnDrawGizmos()
    {
        if (mainCamera != null)
        {
            Vector2 screenCenterPoint = new Vector2(Screen.width / 2f, Screen.height / 2f);
            Ray ray = mainCamera.ScreenPointToRay(screenCenterPoint);
            Gizmos.color = Color.red;
            Gizmos.DrawLine(ray.origin, ray.origin + ray.direction * 100f);
        }
    }
}